<template>
  <scroll-view class="scroll-view"
               :refresher-triggered="refresherTriggered"
               :show-scrollbar="showScrollbar"
               :refresher-threshold="45"
               :lower-threshold="50"
               scroll-y="true"
               :scroll-top="scrollTop"
               showScrollbar
               :refresher-enabled="refresherEnabled"
               @scroll="handleScroll"
               @refresherrestore="onRestore"
               @refresherrefresh="refresherrefresh"
               @scrolltolower="$emit('scrolltolower')">
    <view ref="content">
      <slot></slot>
    </view>

  </scroll-view>
</template>

<script>
export default {
  name: 'xScrollView',
  props: {
    // 开启自定义下拉刷新
    refresherEnabled: {
      type: Boolean,
      default: true
    },
    // 设置自定义下拉刷新阈值
    refresherThreshold: {
      type: Number,
      default: 45
    },
    // 设置竖向滚动条位置
    scrollTop: {
      type: Number,
      default: -1
    },
    // 控制是否出现滚动条
    showScrollbar: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      scrollTopValue: 0,
      refresherTriggered: false, // 设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发
      freshing: false
    };
  },
  methods: {
    refresherrefresh() {
      if (this.freshing) return;
      const rect = this.$refs.content?.$el?.getBoundingClientRect();
      if (rect.top < 0) {
        this.refresherTriggered = false;
        return;
      };
      this.freshing = true;
      this.refresherTriggered = true;
      this.$emit('refresherrefresh', () => {
        this.refresherTriggered = false;
        this.freshing = false;
      });
    },
    handleScroll(event) {
      this.scrollTopValue = event.detail.scrollTop;
      this.$emit('update:scrollTop', this.scrollTopValue);
    },
    onRestore() {
      this.refresherTriggered = 'restore'; // 需要重置
    }
  }
};
</script>

<style scoped>
.scroll-view {
  height: 100%;
}
</style>
